<template>
  <div class="table-info-vue">
    <el-card style="margin: 10px">
      <div slot="header" class="clearfix">
        表信息
        <span style="float: right; margin-top: -5px">
          <el-button
            class="search-submit"
            size="small"
            type="primary"
            icon="el-icon-s-promotion"
            @click="previewTableData"
            >运行SQL</el-button
          >
          <el-button size="small" @click="showCreateTableDdl">DDL</el-button>
        </span>
      </div>
      <div v-if="true">
        <el-row :gutter="24" type="flux" class="status-info-row">
          <el-col
            :span="6"
            class="information-title"
            :title="vueQueryParam.host"
            ><span class="label">数据源：</span>{{ vueQueryParam.host }}</el-col
          >
          <el-col
            :span="6"
            class="information-title"
            :title="vueQueryParam.dbName"
            ><span class="label">数据库：</span
            >{{ vueQueryParam.dbName }}</el-col
          >
          <el-col
            :span="6"
            class="information-title"
            :title="vueQueryParam.dbName"
            ><span class="label">Schema：</span
            >{{ vueQueryParam.dbName }}</el-col
          >
        </el-row>
        <el-row :gutter="20" type="flux" class="status-info-row">
          <el-col
            :span="6"
            class="information-title"
            :title="vueQueryParam.tableName"
            ><span class="label">表名：</span
            >{{ vueQueryParam.tableName }}</el-col
          >
          <el-col
            :span="6"
            class="information-title"
            :title="vueQueryParam.tableType"
            ><span class="label">类型：</span
            >{{ vueQueryParam.tableType }}</el-col
          >
          <el-col
            :span="6"
            class="information-title"
            :title="tableStatusInfo.rows || 0"
            ><span class="label">行数：</span
            >{{ tableStatusInfo.rows || 0 }}</el-col
          >
        </el-row>
        <el-row :gutter="20" type="flux" class="status-info-row">
          <el-col
            :span="6"
            class="information-title"
            :title="getBytesSize(tableStatusInfo.dataLength)"
            ><span class="label">占用空间：</span
            >{{ getBytesSize(tableStatusInfo.dataLength) }}</el-col
          >
          <el-col
            :span="6"
            class="information-title"
            :title="
              tableStatusInfo.createTime ||
              '2020-11-22T03:23:02.000+0000' | dateformat('YYYY-MM-DD')
            "
            ><span class="label">创建时间：</span
            >{{
              tableStatusInfo.createTime ||
              '2020-11-22T03:23:02.000+0000' | dateformat('YYYY-MM-DD')
            }}</el-col
          >
          <el-col
            :span="6"
            class="information-title"
            :title="
              tableStatusInfo.updateTime ||
              '2020-11-22T03:23:02.000+0000' | dateformat('YYYY-MM-DD')
            "
            ><span class="label">最后修改时间：</span
            >{{
              tableStatusInfo.updateTime ||
              '2020-11-22T03:23:02.000+0000' | dateformat('YYYY-MM-DD')
            }}</el-col
          >
        </el-row>
        <el-row type="flux" :gutter="18" class="status-info-row"
          ><el-col
            :span="18"
            class="information-title"
            :title="tableInfo.description"
            ><span class="label">表注释：</span
            >{{ tableInfo.description }}</el-col
          ></el-row
        >
      </div>
    </el-card>
    <el-card style="margin: 10px; width: 62%">
      <div slot="header" class="clearfix">字段信息</div>
      <div style="padding: 10px" v-loading="columnListLoading">
        <el-table
          :highlight-current-row="true"
          :header-cell-style="{
            'text-align': 'center',
            'background-color': '#F1F1F1',
            color: '#333333',
            'font-weight': 'bold',
          }"
          :cell-style="{ 'text-align': 'left' }"
          :data="columnList"
          stripe
          style="width: 100%; margin-bottom: 5px"
          class="tableSearch"
        >
          <el-table-column
            prop="name"
            align="left"
            label="字段名"
            min-width="20%"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <!-- <el-table-column label="自增" width="50">
            <template slot-scope="scope">{{
              scope.row.isidentity ? '是' : '否'
            }}</template>
          </el-table-column> -->
          <el-table-column
            prop="type"
            label="类型"
            align="left"
            min-width="20%"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <!-- <el-table-column
            prop="length"
            label="长度"
            width="80"
          ></el-table-column> -->
          <el-table-column
            label="NULL"
            align="left"
            min-width="20%"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">{{
              scope.row.nullable ? '允许' : '不允许'
            }}</template>
          </el-table-column>
          <el-table-column
            label="主键"
            align="left"
            min-width="20%"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">{{
              scope.row.ispramary ? '是' : '否'
            }}</template>
          </el-table-column>
          <el-table-column
            label="注释"
            align="left"
            min-width="20%"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <div class="description">
                {{ scope.row.description }}
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <!--增加数据源弹窗-->
    <el-dialog
      title="DDL"
      :visible.sync="tableDDLInfoDialogVisible"
      :footer="null"
      width="760px"
    >
      <div v-highlight>
        <pre><code v-html="tableDDLInfo"></code></pre>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import datasourceApi from '../../common/api/datasource'

export default {
  data () {
    return {
      columnListLoading: false,
      vueQueryParam: {},
      tableStatusInfo: {},
      columnList: [],
      tableInfo: {},
      nowExecutorId: 1,
      tableDDLInfo: '',
      tableDDLInfoDialogVisible: false,
    };
  },
  mounted: function () {
    // 延迟设置展开的目录，edit比app先初始化
    setTimeout(() => {
      this.$emit('initLoadDataList', {
        sourceId: this.vueQueryParam.sourceId,
        host: this.vueQueryParam.host,
        dbName: this.vueQueryParam.dbName
      });
    }, 500);
  },
  activated: function () {
    this.initQueryParam(this.$route);
  },
  methods: {
    tableHeaderColor ({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return 'background-color: #F1F1F1;color: #333333;font-weight: bold;'
      }
    },
    initQueryParam (to) {
      if (this.columnListLoading) {
        return;
      }
      this.columnListLoading = true;
      this.vueQueryParam = to.query;
      datasourceApi.tableColumnList(this.vueQueryParam).then(json => {
        let columnList = json.data.columnList || [];
        for (let i = 0; i < columnList.length; i++) {
          columnList[i].inEdit = 0;
          columnList[i].newDesc = columnList[i].description;
        }
        this.columnList = columnList;
        let tableInfo = json.data.tableInfo || {};
        tableInfo.inEdit = 0;
        tableInfo.newDesc = tableInfo.description;
        this.tableInfo = tableInfo;
        let newName = { key: this.$route.fullPath, val: '表-' + tableInfo.tableName };
        this.$store.commit('global/addTableName', newName);
        this.columnListLoading = false;
      });
      datasourceApi.tableStatus(this.vueQueryParam).then(json => {
        this.tableStatusInfo = json.data || {};
      })
    },
    showCreateTableDdl () {
      this.tableDDLInfo = '';
      this.tableDDLInfoDialogVisible = true;
      let param = {
        sourceId: this.vueQueryParam.sourceId,
        dbName: this.vueQueryParam.dbName,
        tableName: this.vueQueryParam.tableName,
      };
      datasourceApi.queryTableDdl(param).then(res => {
        this.tableDDLInfo = res.data || '获取失败';
      });
    },
    descBoxClick (row) {
      // row.newDesc = row.description;
      row.inEdit = 1;
    },
    previewTableData () {
      const that = this.$parent
      let previewParam = {
        sourceId: this.vueQueryParam.sourceId,
        dbName: this.vueQueryParam.dbName,
        tableName: this.vueQueryParam.tableName,
        host: this.vueQueryParam.host,
        dbType: this.vueQueryParam.dbType,
        type: 'preview',
        name: '数据-' + this.vueQueryParam.tableName
      };
      this.$router.push({ path: '/data/executor', query: previewParam }).then(() => {
        that.sqlExecutorEditor = that.initAceEditor("sqlExecutorEditor", 30);
        that.sqlExecutorEditor.setFontSize(this.$store.getters['global/getFont']);
        that.sqlExecutorEditor.commands.addCommand({
          name: "execute-sql",
          bindKey: { win: "Ctrl-R|Ctrl-Shift-R|Ctrl-Enter", mac: "Command-R|Command-Shift-R|Command-Enter" },
          exec: function (editor) {
            that.doExecutorSql();
          }
        })
        that.historyDrawerVisible = false;
      }).catch(err => { err })
    },
    getBytesSize (size) {
      if (!size) return "0 bytes";
      var num = 1024.00;
      if (size < num) return size + " bytes";
      if (size < Math.pow(num, 2)) return (size / num).toFixed(2) + "KB";
      if (size < Math.pow(num, 3)) return (size / Math.pow(num, 2)).toFixed(2) + "MB";
      if (size < Math.pow(num, 4)) return (size / Math.pow(num, 3)).toFixed(2) + "GB";
      return (size / Math.pow(num, 4)).toFixed(2) + "TB";
    },
    saveColumnDescription (row) {
      if (row.inEdit == 0 || row.description == row.newDesc) {
        row.inEdit = 0;
        return;
      }
      row.inEdit = 0;
      this.vueQueryParam.columnName = row.name;
      this.vueQueryParam.newDesc = row.newDesc;
      datasourceApi.updateTableColumnDesc(this.vueQueryParam).then(() => {
        row.description = row.newDesc;
        this.$message.success("修改成功");
      });
    },
    saveTableDescription () {
      if (this.tableInfo.inEdit == 0 || this.tableInfo.description == this.tableInfo.newDesc) {
        this.tableInfo.inEdit = 0;
        return;
      }
      this.tableInfo.inEdit = 0;
      this.vueQueryParam.newDesc = this.tableInfo.newDesc;
      datasourceApi.updateTableDesc(this.vueQueryParam).then(() => {
        this.tableInfo.description = this.tableInfo.newDesc;
        this.$message.success("修改成功");
      });
    },
  }
}
</script>
<style>
.table-info-vue .el-dialog__body {
  padding: 0 20px 10px;
}
.table-info-vue .el-form-item {
  margin-bottom: 5px;
}
.table-info-vue .edit-table-desc {
  cursor: pointer;
  color: #409eff;
}
.table-info-vue .description {
  cursor: pointer;
  min-height: 23px;
}
.table-info-vue .el-table td,
.table-info-vue .el-table th {
  padding: 5px 0;
}

.table-info-vue .status-info-row .label {
  padding: 10px;
  display: inline-block;
  text-align: right;
  color: #606266;
}

.information-title {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.el-card__header {
  padding: 12px 20px;
  background-color: #64b4e8;
}
</style>

